package org.xiaov.rabbitmq.consumer;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.xiaov.common.bean.rabbitmq.QueueChain;
import org.xiaov.common.bean.rabbitmq.QueueGroup;
import org.xiaov.entity.po.UserPo;
import org.xiaov.framework.constant.ApiR;
import org.xiaov.rabbitmq.fregin.ConsumerClient;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * <p>
 * 描述：
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/12/24 23:13
 */
@Component
@Slf4j
public class RabbitmqConsumer {

    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    private QueueChain queueChain;

    @Resource
    private ConsumerClient consumerClient;

    @RabbitHandler
    @RabbitListener(queues = "${v.rabbitmq.email.queue}")
    public void processEmailQueue(Message message) {
        MessageProperties properties = message.getMessageProperties();
        String id = new String(message.getBody());
        log.info("从mq获取到数据id：：{}", id);
        ApiR<UserPo> userDTO = consumerClient.getUserById(id);
        UserPo user = userDTO.getData();
        log.info("查询到用户：{}", user);
        user.setAmount(new BigDecimal("100"));
        user.setModifiedon(LocalDateTime.now());
        consumerClient.edit(user);
    }

    @RabbitHandler
    @RabbitListener(queues = "${v.rabbitmq.dead.queue}")
    public void processDeadQueue(Message message) {
        MessageProperties properties = message.getMessageProperties();
        String messageStr = new String(message.getBody());
        QueueGroup nextQueue = getNextQueue(queueChain, properties);
        log.info("nextQueue:{}", nextQueue);
        rabbitTemplate.convertAndSend(nextQueue.getQueueExchange(), nextQueue.getQueueRouteKey(), messageStr);
        log.info("queueChain:{}，properties：{}", queueChain, properties);
    }

    public static QueueGroup getNextQueue(QueueChain queueChain, MessageProperties properties) {
        Map<String, Object> header = properties.getHeaders();
        Object preQueueNameObj = header.get("x-first-death-queue");

        String preQueueName = null;
        if (preQueueNameObj != null) {
            preQueueName = preQueueNameObj.toString();
        }

        // 如果这个参数为空 说明这不是从延时队列过来的数据  应该是直接塞到死信队列的数据
        // 这个时候如果还需要再次触发查询 就放到我们延时队列链的第一个延时队列里面去
        if (StrUtil.isEmpty(preQueueName)) {
            return queueChain.getFirstQueue();
        }

        QueueGroup nextQueue = queueChain.getNextQueueName(preQueueName);
        if (nextQueue == null) {
            nextQueue = queueChain.getFirstQueue();
        }

        return nextQueue;
    }
}
